package com.stox.client.ui.javafx.chartingy.model.node;

import javafx.scene.paint.Color;
import javafx.scene.shape.Line;

import com.stox.client.ui.javafx.chartingy.model.Rectangle;
import com.stox.client.ui.javafx.chartingy.model.plot.Data;
import com.stox.client.ui.javafx.chartingy.model.plot.PricePlot;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.Scrip;

public class OHLC extends AbstractPriceNode {
	
	private Line highLowLine = new Line();
	private Line closeLine = new Line();
	private Line openLine = new Line();

	public OHLC(Data<Scrip, Bar> data) {
		super(data);
		
		getChildren().addAll(openLine, closeLine, highLowLine);
		UI.style(this, CSS.barNode);
		
		highLowLine.endXProperty().bind(highLowLine.startXProperty());
		closeLine.strokeWidthProperty().bind(highLowLine.strokeWidthProperty());
		closeLine.endYProperty().bind(closeLine.startYProperty());
		closeLine.startXProperty().bind(highLowLine.startXProperty());
		openLine.strokeWidthProperty().bind(highLowLine.strokeWidthProperty());
		openLine.endYProperty().bind(openLine.startYProperty());
		openLine.endXProperty().bind(highLowLine.startXProperty());
		openLine.strokeProperty().bindBidirectional(closeLine.strokeProperty());
		
		updateColor();
	}

	@Override
	public void layoutChartChildren() {
		Data<Scrip,Bar> data = getData();
		Bar bar = (Bar)data.getExtraValue();
		
		double high = getDisplayPosition(bar.getHigh());
		double low = getDisplayPosition(bar.getLow());
		Rectangle rectangle = getRectangle();
		rectangle.setY(high);
		rectangle.setHeight(low - high);
		double width = rectangle.getWidth();
		double x = rectangle.getX() + width/2;
		
		rectangle.setX(x - width/2);
		rectangle.setWidth(width);
		rectangle.setY(high);
		rectangle.setHeight(low - high);
		
		width = width*(1-data.chartingView().getBarGap());
		
		double strokeWidth = 5 < width ? width/5 : 1;
		highLowLine.setStrokeWidth(strokeWidth);
		
		highLowLine.setStartX(x);
		highLowLine.setStartY(high);
		highLowLine.setEndY(low);
		
		closeLine.setStartY(getDisplayPosition(bar.getClose()));
		closeLine.setEndX(closeLine.getStartX() + width/2);
		
		openLine.setStartY(getDisplayPosition(bar.getOpen()));
		openLine.setStartX(x - width/2);
		
}
	
	@Override
	public void updateColor(){
		PricePlot plot = (PricePlot)getData().getPlot();
		Color color = null == up ? plot.getColor() : up ? plot.getUpBarColor() : plot.getDownBarColor();
		setStyle("-fx-bar-color:"+UI.web(color)+";");
	}
	
}
